package com.yuantong.xyerp.rest.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.yuantong.xyerp.core.api.common.Constant;
import com.yuantong.xyerp.core.api.dto.ContractDto;
import com.yuantong.xyerp.core.api.form.QueryForm;
import com.yuantong.xyerp.core.api.model.UserDetail;
import com.yuantong.xyerp.core.provider.dao.ContractMapper;
import com.yuantong.xyerp.rest.controller.base.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 业务类型：B-采购；S-销售
 * Created by Jianguo.Yin on 2021-08-04.
 */
@Slf4j
@RestController
@RequestMapping("/sales")
@Api(tags = "销售单管理")
public class SalesController extends BaseController {

    private final String businessType = "S";

    @Resource
    private ContractMapper contractMapper;


    private Map<String, ExcelExportEntity> getSaleContractColumns() {
        Map<String, ExcelExportEntity> saleContractColumns = new HashMap<>();

        ExcelExportEntity exportEntity = new ExcelExportEntity("提交时间", "createTime", 40);
        exportEntity.setFormat("yyyy-MM-dd");

        ExcelExportEntity exportEntity7 = new ExcelExportEntity("出货方式", "transportType",40);
        exportEntity7.setReplace(new String[]{"自提_S", "配送_D"});

        ExcelExportEntity exportEntity10 = new ExcelExportEntity("流程状态", "nextProcessState",40);
        exportEntity10.setReplace(new String[]{"仓库管理员审批_warehouseExamine","销售主管复审_managerReexamline",
                "销售主管审批_managerExamine","销售内勤审批_officeExamine","初审驳回_reject","保存_save",
                "出纳审核（结算）_cashierExamine3","完成_finish","销售副总审批_vicePresidentExamine",
                "出纳审核（配送）_cashierExammine2","出纳审核（自提）_cashierExammine1"});

        saleContractColumns.put("提交时间",exportEntity);
        saleContractColumns.put("合同编号",new ExcelExportEntity("合同编号", "contractNo",40));
        saleContractColumns.put("客户名称",new ExcelExportEntity("客户名称", "merchantName",40));
        saleContractColumns.put("品类",new ExcelExportEntity("品类", "categoryName",40));
        saleContractColumns.put("合同金额（元）",new ExcelExportEntity("合同金额（元）", "totalPayment",40));
        saleContractColumns.put("销售重量（吨）",new ExcelExportEntity("销售重量（吨）" ,"totalWeight",40));
        saleContractColumns.put("出库仓库",new ExcelExportEntity("出库仓库", "warehouseName",40));
        saleContractColumns.put("出货方式",exportEntity7);
        saleContractColumns.put("销售人员",new ExcelExportEntity("销售人员", "signName",40));
        saleContractColumns.put("创建人",new ExcelExportEntity("创建人", "creatorName",40));
        saleContractColumns.put("流程状态",exportEntity10);
        saleContractColumns.put("预收款（元）",new ExcelExportEntity("预收款（元）", "advancePayment",40));
        saleContractColumns.put("收款金额（元）",new ExcelExportEntity("收款金额（元）", "actualPayment",40));
        saleContractColumns.put("应收金额（元）",new ExcelExportEntity("应收金额（元）", "actualReceivable",40));
        saleContractColumns.put("入库重量（吨）",new ExcelExportEntity("出库重量（吨）" ,"actualWeight",40));
        return saleContractColumns;
    }

    // 关于自定义导出数据, 前端传dto 导出合同基本信息/采购单/销售单
    /**
     * 销售单导出
     */
    @ApiOperation(value = "导出销售单",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export/salesList", produces = "application/octet-stream;charset=utf-8")
    public void salesList(HttpServletResponse response,
                          HttpServletRequest request,
                          @ApiParam("查询参数") @RequestBody QueryForm queryForm) {
        // 加  个人数据 部门数据 全部数据 的查询条件
        String causeId = getCauseId(request);

        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        Map<String, ExcelExportEntity> map = getSaleContractColumns();

        // 销售单汇总
        entity.add(map.get("提交时间"));
        entity.add(map.get("合同编号"));
        entity.add(map.get("客户名称"));
        entity.add(map.get("品类"));
        entity.add(map.get("合同金额（元）"));
        entity.add(map.get("销售重量（吨）"));
        entity.add(map.get("出库仓库"));
        entity.add(map.get("出货方式"));
        entity.add(map.get("销售人员"));
        entity.add(map.get("创建人"));
        entity.add(map.get("流程状态"));

        List<ContractDto> list = contractMapper.findAllByFuzzy(
                businessType, queryForm.getStateType(), queryForm.getStartTime(), queryForm.getEndTime(), queryForm.getFuzzy(), queryForm.getLowerAmount(), queryForm.getHigherAmount(), queryForm.getIds(),causeId);

        String fileName = "销售单列表";
        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            /**用 流的形式 */
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 销售主管初审导出
     */
    @ApiOperation(value = "销售主管初审导出",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export/saleManagerExamine", produces = "application/octet-stream;charset=utf-8")
    public void saleManagerExamine(HttpServletResponse response,
                          HttpServletRequest request,
                          @ApiParam("查询参数") @RequestBody QueryForm queryForm) {
        // 加  个人数据 部门数据 全部数据 的查询条件
        String causeId = getCauseId(request);
        String stateType = Constant.state_managerExamine;
        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        Map<String, ExcelExportEntity> map = getSaleContractColumns();

        entity.add(map.get("提交时间"));
        entity.add(map.get("合同编号"));
        entity.add(map.get("客户名称"));
        entity.add(map.get("品类"));
        entity.add(map.get("合同金额（元）"));
        entity.add(map.get("销售重量（吨）"));
        entity.add(map.get("出库仓库"));
        entity.add(map.get("出货方式"));
        entity.add(map.get("销售人员"));
        entity.add(map.get("创建人"));

        List<ContractDto> list = contractMapper.findAllByFuzzy(
                businessType, stateType, queryForm.getStartTime(), queryForm.getEndTime(), queryForm.getFuzzy(), queryForm.getLowerAmount(), queryForm.getHigherAmount(), queryForm.getIds(),causeId);

        String fileName = "销售主管初审列表";
        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            /**用 流的形式 */
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 销售副总审核导出
     */
    @ApiOperation(value = "销售副总审核导出",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export/saleVicePresidentExamine", produces = "application/octet-stream;charset=utf-8")
    public void saleVicePresidentExamine(HttpServletResponse response,
                          HttpServletRequest request,
                          @ApiParam("查询参数") @RequestBody QueryForm queryForm) {
        // 加  个人数据 部门数据 全部数据 的查询条件
        String causeId = getCauseId(request);
        String stateType = Constant.state_vicePresidentExamine;

        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        Map<String, ExcelExportEntity> map = getSaleContractColumns();

        entity.add(map.get("提交时间"));
        entity.add(map.get("合同编号"));
        entity.add(map.get("客户名称"));
        entity.add(map.get("品类"));
        entity.add(map.get("合同金额（元）"));
        entity.add(map.get("销售重量（吨）"));
        entity.add(map.get("收款金额（元）"));
        entity.add(map.get("出库仓库"));
        entity.add(map.get("出货方式"));
        entity.add(map.get("销售人员"));

        List<ContractDto> list = contractMapper.findAllByFuzzy(
                businessType, stateType, queryForm.getStartTime(), queryForm.getEndTime(), queryForm.getFuzzy(), queryForm.getLowerAmount(), queryForm.getHigherAmount(), queryForm.getIds(),causeId);

        String fileName = "销售副总审核导出";
        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            /**用 流的形式 */
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 出纳审核（自提）导出
     * "出纳审核（结算）_cashierExamine3",
     * "出纳审核（配送）_cashierExammine2","出纳审核（自提）_cashierExammine1"
     */
    @ApiOperation(value = "出纳审核（自提）导出",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export/saleCashierExamine1", produces = "application/octet-stream;charset=utf-8")
    public void saleCashierExamine1(HttpServletResponse response,
                                   HttpServletRequest request,
                                   @ApiParam("查询参数") @RequestBody QueryForm queryForm) {
        // 加  个人数据 部门数据 全部数据 的查询条件
        String causeId = getCauseId(request);
        String stateType = Constant.state_cashierExammine1; // 出纳有不同的状态 可以单独开个请iu

        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        Map<String, ExcelExportEntity> map = getSaleContractColumns();

        entity.add(map.get("提交时间"));
        entity.add(map.get("合同编号"));
        entity.add(map.get("客户名称"));
        entity.add(map.get("品类"));
        entity.add(map.get("合同金额（元）"));
        entity.add(map.get("销售重量（吨）"));
        entity.add(map.get("出库仓库"));
        entity.add(map.get("出货方式"));
        entity.add(map.get("销售人员"));

        List<ContractDto> list = contractMapper.findAllByFuzzy(
                businessType, stateType, queryForm.getStartTime(), queryForm.getEndTime(), queryForm.getFuzzy(), queryForm.getLowerAmount(), queryForm.getHigherAmount(), queryForm.getIds(),causeId);

        String fileName = "销售出纳审核（自提）列表";
        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            /**用 流的形式 */
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 出纳审核（配送）导出
     * "出纳审核（结算）_cashierExamine3",
     * "出纳审核（配送）_cashierExammine2","出纳审核（自提）_cashierExammine1"
     */
    @ApiOperation(value = "出纳审核（配送）导出",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export/saleCashierExamine2", produces = "application/octet-stream;charset=utf-8")
    public void saleCashierExamine2(HttpServletResponse response,
                                   HttpServletRequest request,
                                   @ApiParam("查询参数") @RequestBody QueryForm queryForm) {
        // 加  个人数据 部门数据 全部数据 的查询条件
        String causeId = getCauseId(request);
        String stateType = Constant.state_cashierExammine1; // 出纳有不同的状态 可以单独开个请iu

        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        Map<String, ExcelExportEntity> map = getSaleContractColumns();

        entity.add(map.get("提交时间"));
        entity.add(map.get("合同编号"));
        entity.add(map.get("客户名称"));
        entity.add(map.get("品类"));
        entity.add(map.get("合同金额（元）"));
        entity.add(map.get("销售重量（吨）"));
        entity.add(map.get("出库仓库"));
        entity.add(map.get("出货方式"));
        entity.add(map.get("销售人员"));

        List<ContractDto> list = contractMapper.findAllByFuzzy(
                businessType, stateType, queryForm.getStartTime(), queryForm.getEndTime(), queryForm.getFuzzy(), queryForm.getLowerAmount(), queryForm.getHigherAmount(), queryForm.getIds(),causeId);

        String fileName = "销售出纳审核（配送）列表";
        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            /**用 流的形式 */
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 出纳审核（结算）导出
     * "出纳审核（结算）_cashierExamine3",
     * "出纳审核（配送）_cashierExammine2","出纳审核（自提）_cashierExammine1"
     */
    @ApiOperation(value = "出纳审核（结算）导出",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export/cashierExamine3", produces = "application/octet-stream;charset=utf-8")
    public void saleCashierExamine3(HttpServletResponse response,
                                    HttpServletRequest request,
                                    @ApiParam("查询参数") @RequestBody QueryForm queryForm) {
        // 加  个人数据 部门数据 全部数据 的查询条件
        String causeId = getCauseId(request);
        String stateType = Constant.state_cashierExamine3; // 出纳有不同的状态 可以单独开个请iu

        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        Map<String, ExcelExportEntity> map = getSaleContractColumns();

        entity.add(map.get("提交时间"));
        entity.add(map.get("合同编号"));
        entity.add(map.get("客户名称"));
        entity.add(map.get("品类"));
        entity.add(map.get("合同金额（元）"));
        entity.add(map.get("销售重量（吨）"));
        entity.add(map.get("出库仓库"));
        entity.add(map.get("出货方式"));
        entity.add(map.get("销售人员"));

        List<ContractDto> list = contractMapper.findAllByFuzzy(
                businessType, stateType, queryForm.getStartTime(), queryForm.getEndTime(), queryForm.getFuzzy(), queryForm.getLowerAmount(), queryForm.getHigherAmount(), queryForm.getIds(),causeId);

        String fileName = "出纳审核（结算）列表";
        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            /**用 流的形式 */
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    /**
     * 销售内勤审批
     */
    @ApiOperation(value = "销售内勤审批导出",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export/saleOfficeExamine", produces = "application/octet-stream;charset=utf-8")
    public void saleOfficeExamine(HttpServletResponse response,
                                   HttpServletRequest request,
                                   @ApiParam("查询参数") @RequestBody QueryForm queryForm) {
        // 加  个人数据 部门数据 全部数据 的查询条件
        String causeId = getCauseId(request);

        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        Map<String, ExcelExportEntity> map = getSaleContractColumns();

        entity.add(map.get("提交时间"));
        entity.add(map.get("合同编号"));
        entity.add(map.get("客户名称"));
        entity.add(map.get("品类"));
        entity.add(map.get("合同金额（元）"));
        entity.add(map.get("销售重量（吨）"));
        entity.add(map.get("收款金额（元）"));
        entity.add(map.get("出库仓库"));
        entity.add(map.get("出货方式"));
        entity.add(map.get("销售人员"));

        String stateType = Constant.state_officeExamine;
        List<ContractDto> list = contractMapper.findAllByFuzzy(
                businessType, stateType, queryForm.getStartTime(), queryForm.getEndTime(), queryForm.getFuzzy(), queryForm.getLowerAmount(), queryForm.getHigherAmount(), queryForm.getIds(),causeId);

        String fileName = "销售单主管初审列表";
        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            /**用 流的形式 */
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 销售单导出 销售主管复审核
     */
    @ApiOperation(value = "销售主管复审核导出",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export/saleManagerReexamline", produces = "application/octet-stream;charset=utf-8")
    public void saleManagerReexamline(HttpServletResponse response,
                                      HttpServletRequest request,
                                      @ApiParam("查询参数") @RequestBody QueryForm queryForm) {
        // 加  个人数据 部门数据 全部数据 的查询条件
        String causeId = getCauseId(request);

        String stateType = Constant.state_officeReexamine;

        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        Map<String, ExcelExportEntity> map = getSaleContractColumns();

        entity.add(map.get("提交时间"));
        entity.add(map.get("合同编号"));
        entity.add(map.get("客户名称"));
        entity.add(map.get("品类"));
        entity.add(map.get("合同金额（元）"));
        entity.add(map.get("出库重量（吨）"));
        entity.add(map.get("应收金额（元）"));
        entity.add(map.get("收款金额（元）"));
        entity.add(map.get("销售人员"));


        List<ContractDto> list = contractMapper.findAllByFuzzy(
                businessType, stateType, queryForm.getStartTime(), queryForm.getEndTime(), queryForm.getFuzzy(), queryForm.getLowerAmount(), queryForm.getHigherAmount(), queryForm.getIds(),causeId);

        String fileName = "销售主管复审列表";
        Workbook workbook = ExcelExportUtil
                .exportExcel(new ExportParams(fileName, fileName, ExcelType.HSSF), entity, list);

        ServletOutputStream outputStream = null;
        try {
            /**用 流的形式 */
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
